import { Accessor, createEffect, createMemo, createSignal } from "solid-js";

export const createDelay = (
    signal: Accessor<boolean | undefined>,
    options?: { delay?: number; initial?: boolean }
) => {
    const [relay, setRelay] = createSignal(options?.initial ?? false);
    const [delay, setDelay] = createSignal<NodeJS.Timeout | null>();

    createEffect(() => {
        const currentValue = signal();
        console.log('delay(changed)', currentValue)
        if (currentValue) {
            if (delay()) {
                console.log('delay(changed)delaied', currentValue)
                return;
            } else {
                setDelay(setTimeout(() => setRelay(true), options?.delay ?? 500));
            }
        } else {
            setDelay((v) => {
                if (v) {
                    clearTimeout(v);
                }
                return null;
            });

            setRelay(false);
        }
    });

    return createMemo(() => relay());
};
